package com.pf.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author PanFei
 * @version 1.0.0
 * @createTime 2021/9/4
 */
@Slf4j
public class JacksonUtils {

    private static final ObjectMapper objectMapper = createObjectMapper();


    public static ObjectMapper createObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        //反序列化：禁止遇到未知（新）属性时报错，支持兼容扩展。
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //如果是空对象的时候,不抛异常
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
        return objectMapper;
    }

    /**
     * 对象转为JSON字符串
     *
     * @param obj
     * @return
     */
    public static String toJsonString(Object obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.error("JacksonUtils -> toJsonString error", e);
        }
        return null;
    }

    /**
     * json字符串反序列化为自定义引用类型
     *
     * @param jsonStr
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T toObject(String jsonStr, Class<T> clazz) {
        try {
            return objectMapper.readValue(jsonStr, clazz);
        } catch (JsonProcessingException e) {
            log.error("JacksonUtils -> readValue error", e);
        }
        return null;
    }

    /**
     * 将json字符串转为 List<T>
     *
     * @param jsonStr
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> List<T> toList(String jsonStr, Class<T> clazz) {
        try {
            return objectMapper.readValue(jsonStr, new TypeReference<List<T>>() {
            });
        } catch (Exception e) {
            log.error("JacksonUtils -> toList error", e);
        }
        return Lists.newArrayList();
    }
}
